local M = {}

local capabilities = require('cmp_nvim_lsp').default_capabilities(vim.lsp.protocol.make_client_capabilities())
local global = require('core.global')

local function get_binary_path(binary)
  local path = nil
  if global.is_mac or global.is_linux then
    path = vim.fn.trim(vim.fn.system('which ' .. binary))
  elseif global.is_windows then
    path = vim.fn.trim(vim.fn.system('where ' .. binary))
  end
  if vim.v.shell_error ~= 0 then
    path = nil
  end
  return path
end

local function get_binary_path_list(binaries)
  local path_list = {}
  for _, binary in ipairs(binaries) do
    local path = get_binary_path(binary)
    if path then
      table.insert(path_list, path)
    end
  end
  return table.concat(path_list, ',')
end

local options = {
  capabilities = vim.tbl_deep_extend('keep', {
    offsetEncoding = { 'utf-16', 'utf-8' },
  }, capabilities),
  lsp_flags = { debounce_text_changes = 150 },
  cmd = {
    'clangd',
    '--background-index',
    '--pch-storage=memory',
    '--query-driver=' .. get_binary_path_list({ 'clang++', 'clang', 'gcc', 'g++' }),
    '--clang-tidy',
    '--all-scopes-completion',
    '--completion-style=detailed',
    '--header-insertion-decorators',
    '--header-insertion=iwyu',
  },
}

M.setup = function(server)
  server.setup(options)
end

return M
